﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Security.Permissions;
using System.Web;
using System.Windows.Forms;
using System.Threading;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
            string username = "dennis_zsc";
            string password = "dennis&quiet";

            string subject = "This is subject";
            string body = "This is a message body";

            HexunMicroblogging hexun = new HexunMicroblogging();
            if (hexun.LoginFromDefaultPage(username, password))
            {
                hexun.IssueMicrobloggingText();
                System.Console.WriteLine("Blog successfully!");
            }
            else
            {
                System.Console.WriteLine("Login failed");
            }
            */

            //TestWebBroswer();
            var t = new Thread(TestWebBroswer);
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }

        private static void TestWebBroswer()
        {
            WebBrowser browser = new WebBrowser();
            browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
            browser.Navigate("http://t.hexun.com/default.htm");
        }

        private static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string userName = "dennis_zsc";
            string password = "dennis&quiet";

            WebBrowser b = sender as WebBrowser;
            bool fillAndClickLoginResult = FillFormAndClickLogin(b.Document, userName, password);
            if (!fillAndClickLoginResult)
            {
                foreach (HtmlWindow frameWindow in b.Document.Window.Frames)
                {
                    try
                    {
                        bool fillAndClickLoginInInnerform = FillFormAndClickLogin(frameWindow.Document, userName, password);
                        if (fillAndClickLoginInInnerform)
                        {
                            break;
                        }
                    }
                    catch { }
                }
            }

            /*
            bool findLoginBtn = false;
            HtmlElementCollection elements = b.Document.GetElementsByTagName("input");
            foreach (HtmlElement element in elements)
            {
                if (element.Name == "username")
                {
                    string innerHtml = element.InnerHtml;
                    element.SetAttribute("value", userName);
                }
                else if (element.Name == "password")
                {
                    string innerHtml = element.InnerHtml;
                    element.SetAttribute("value", password);
                }
                else// (element.Name == "login")
                {
                    string innerHtml = element.InnerHtml;
                    //<input type="button" onclick="javascript:login();" value="" class="indlogin_btn">
                    
                    string typeButton = "type=\"button\"";
                    string typeButton2 = "type='button'";

                    string classIndLoginBtn = "class=\"indlogin_btn\"";
                    string classIndLoginBtn2 = "class='indlogin_btn'";

                    if ((innerHtml.Contains(typeButton) || innerHtml.Contains(typeButton2)) &&
                        (innerHtml.Contains(classIndLoginBtn) || innerHtml.Contains(classIndLoginBtn2)))
                    {
                        findLoginBtn = true;
                        element.InvokeMember("click");
                    }
                }
            }

            if (!findLoginBtn)
            {
                
            }
            */

            /*
            string response = b.DocumentText;

            // looks in the page source to find the authenticity token.
            // could also use regular expressions here.
            int index = response.IndexOf("authenticity_token");
            int startIndex = index + 41;
            string authenticityToken = response.Substring(startIndex, 40);

            // unregisters the first event handler
            // adds a second event handler
            b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
            b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted2);

            // format our data that we are going to post to the server
            // this will include our post parameters.  They do not need to be in a specific
            // order, as long as they are concatenated together using an ampersand ( & )
            string username = string.Empty;
            string password = string.Empty;
            string commit = string.Empty;
            string postData = string.Format("authenticity_token={2}&session[username_or_email]={0}&session[password]={1}&commit={3}", username, password, authenticityToken, commit);

            ASCIIEncoding enc = new ASCIIEncoding();

            //  we are encoding the postData to a byte array
            b.Navigate("https://twitter.com/sessions", "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n");
            */
        }

        private static void browser_DocumentCompleted2(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser b = sender as WebBrowser;
            string response = b.DocumentText;
            if (response.Contains("Sign out"))
            {
                MessageBox.Show("Login Successful");
            }
        }

        private static bool FillFormAndClickLogin(HtmlDocument doc, string userName, string password)
        {
            if (doc == null) return false;
            HtmlElementCollection elements = doc.GetElementsByTagName("input");
            foreach (HtmlElement element in elements)
            {
                if (element.Name == "username")
                {
                    string innerHtml = element.InnerHtml;
                    element.SetAttribute("value", userName);
                }
                else if (element.Name == "password")
                {
                    string innerHtml = element.InnerHtml;
                    element.SetAttribute("value", password);
                }
                else// (element.Name == "login")
                {
                    string innerHtml = element.InnerHtml;
                    //<input type="button" onclick="javascript:login();" value="" class="indlogin_btn">

                    string typeButton = "type=\"button\"";
                    string typeButton2 = "type='button'";

                    string classIndLoginBtn = "class=\"indlogin_btn\"";
                    string classIndLoginBtn2 = "class='indlogin_btn'";

                    if ((innerHtml.Contains(typeButton) || innerHtml.Contains(typeButton2)) &&
                        (innerHtml.Contains(classIndLoginBtn) || innerHtml.Contains(classIndLoginBtn2)))
                    {
                        //findLoginBtn = true;
                        element.InvokeMember("click");
                        return true;
                    }
                }
            }

            return false;
        }

        private static bool FillFormAndClickLogin(WebBrowser webBrowser, string userName, string password)
        {
            if (webBrowser == null) return false;
            HtmlElementCollection elements = webBrowser.Document.GetElementsByTagName("input");
            foreach (HtmlElement element in elements)
            {
                if (element.Name == "username")
                {
                    string innerHtml = element.InnerHtml;
                    element.SetAttribute("value", userName);
                }
                else if (element.Name == "password")
                {
                    string innerHtml = element.InnerHtml;
                    element.SetAttribute("value", password);
                }
                else// (element.Name == "login")
                {
                    string innerHtml = element.InnerHtml;
                    //<input type="button" onclick="javascript:login();" value="" class="indlogin_btn">

                    string typeButton = "type=\"button\"";
                    string typeButton2 = "type='button'";

                    string classIndLoginBtn = "class=\"indlogin_btn\"";
                    string classIndLoginBtn2 = "class='indlogin_btn'";

                    if ((innerHtml.Contains(typeButton) || innerHtml.Contains(typeButton2)) &&
                        (innerHtml.Contains(classIndLoginBtn) || innerHtml.Contains(classIndLoginBtn2)))
                    {
                        //findLoginBtn = true;
                        element.InvokeMember("click");
                        return true;
                    }
                }
            }

            return false;
        }






        private static void testLogin()
        {
            string strLoginName = "dennis_zsc";
            string strPassword = "dennis&quiet";

            try
            {
                string loginUir = "http://reg.hexun.com/login.aspx";
                //loginUir += "?gourl=http://t.hexun.com/home.html";
                //string loginReferUri = "http://t.hexun.com/rest/indexlogin.aspx";

                string strURL = loginUir;
                //string strPostData = String.Format("login={0}&passwd={1}", strLoginName.Trim(), strPassword.Trim());
                string strPostData = string.Format("TextBoxUserName={0}&TextBoxPassword={1}", strLoginName, strPassword);

                // Setup the http request.
                HttpWebRequest webReq = WebRequest.Create(strURL) as HttpWebRequest;
                webReq.Method = "POST";
                webReq.ContentLength = strPostData.Length;
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.AllowAutoRedirect = true;
                webReq.CookieContainer = new CookieContainer();

                // Post to the login form.
                StreamWriter streamRequestWriter = new StreamWriter(webReq.GetRequestStream());
                streamRequestWriter.Write(strPostData);
                streamRequestWriter.Close();

                // Get the response.
                HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();

                // Have some cookies.
                CookieCollection cookieCollection = webResp.Cookies;

                // Read the response

                Stream datastream = webResp.GetResponseStream();
                StreamReader reader = new StreamReader(datastream, System.Text.Encoding.GetEncoding(webResp.CharacterSet), true);
                String strResponseFromServer = reader.ReadToEnd();

                Console.WriteLine(strResponseFromServer);
                Console.ReadLine();
            }

            catch (WebException e)
            {
                Console.WriteLine("\nMain 1 Exception raised!");
                Console.WriteLine("\nMessage 1:{0}", e.Message);
                Console.WriteLine("\nStatus 1:{0}", e.Status);
                Console.WriteLine("Press any key to continue..........");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nMain 2 Exception raised!");
                Console.WriteLine("Source 2:{0} ", e.Source);
                Console.WriteLine("Message 2:{0} ", e.Message);
                Console.WriteLine("Press key to continue..........");
                Console.ReadLine();
            }
        }
    }
}
